package com.telenav.snowsweeper.data;

import java.util.Vector;

import com.telenav.snowsweeper.renderer.Util;

import android.graphics.Rect;

public class EdgeMap {
	private Edge[][] verticalEdges;			// 6 * 9
	private Edge[][] horizontalEdges;		// 7 * 8
	
	public EdgeMap(int[][] vPosTransTimes, int[][] vNegTransTimes, int[][] hPosTransTimes, int[][] hNegTransTimes) throws InitException {
		try {
			verticalEdges = new Edge[vPosTransTimes.length][];
			for (int i = 0; i < vPosTransTimes.length; ++i) {
				verticalEdges[i] = new Edge[vPosTransTimes[i].length];
				for (int j = 0; j < vPosTransTimes[i].length; ++j) {
					if (vPosTransTimes[i][j] > 0 || vNegTransTimes[i][j] > 0) {
						verticalEdges[i][j] = new Edge(i << 24 | j << 16, vPosTransTimes[i][j], vNegTransTimes[i][j], 
								PointsManager.getPoint(i, j), PointsManager.getPoint(i + 1, j));
					}
				}
			}
			
			horizontalEdges = new Edge[hPosTransTimes.length][];
			for (int i = 0; i < hPosTransTimes.length; ++i) {
				horizontalEdges[i] = new Edge[hPosTransTimes[i].length];
				for (int j = 0; j < hPosTransTimes[i].length; ++j) {
					if (hPosTransTimes[i][j] > 0 || hNegTransTimes[i][j] > 0)
						horizontalEdges[i][j] = new Edge(i << 8 | j, hPosTransTimes[i][j], hNegTransTimes[i][j],
								PointsManager.getPoint(i, j), PointsManager.getPoint(i, j + 1));
				}
			}
		}
		catch (Exception e) {
			throw new InitException();
		}
	}
	
	public Edge getHorEdge(int row, int col) {
		if (row < horizontalEdges.length && col < horizontalEdges[row].length) {
			return horizontalEdges[row][col];
		}
		return null;
	}
	
	public Edge getVertEdge(int row, int col) {
		if (row < verticalEdges.length && col < verticalEdges[row].length) {
			return verticalEdges[row][col];
		}
		return null;
	}
	
	public void clipEdges(Rect clip, Vector<Edge> collection) {
		int left = Util.x2TileColumn(clip.left);
		int right = Util.x2TileColumn(clip.right);
		int top = Util.y2TileRow(clip.top);
		int bottom = Util.y2TileRow(clip.bottom);
		
		int temp = right + 1;
		for (int i = top; i <= bottom; ++i) {
			for (int j = left; j <= temp; ++j) {
				if (verticalEdges[i][j] != null)
					collection.add(verticalEdges[i][j]);
			}
		}
		
		temp = bottom + 1;
		for (int i = top; i <= temp; ++i) {
			for (int j = left; j <= right; ++j) {
				if (horizontalEdges[i][j] != null)
					collection.add(horizontalEdges[i][j]);
			}
		}
	}
	
	public class InitException extends Exception {
		private static final long serialVersionUID = 1L;
	}
}
